<?php


if(Antz_IntelliForm::submitted('IUsers_Register', false)){
    Antz_IntelliForm::save('register');
}else{
    Antz_IntelliForm::restore('register');
};


$CRYPT = Antz::registry('crypt');
$DB = Antz::registry('db');

$defaultCountry = $this->GetConfig('default_country');

// which fields to show
$showFields = explode(',', $this->GetConfig('register_show_fields'));

if(Antz_IntelliForm::submitted('IUsers_Register')){

    // process to create a new user
    $busname = post('business_name');
    $username = post('username');
    $email = post('email');
    $emailMD5 = md5(strtolower($email));
    $password = post('password');
    $confirmPassword = post('confirm_password');
    $fName = post('first_name');
    $lName = post('last_name');
    $country = preg_replace('/[^a-zA-Z0-9]/', '', post('country', $defaultCountry));
    $city = (int) post('city', 0);
    $groups = explode(',', trim($this->GetConfig('default_groups_for_self_registration'), ' ,'));
    $tnc = (int) post('tnc');
    $subscribe = (int) post('subscribe', $this->GetConfig('auto_subscribe_new_users'));
    $dob = post('dob');
    $sex = post('sex', '0');

    // begin checks
    $error = false;

    if(trim($username) == ''){
	    $error = true;
    	Antz::addFormError('username', $this->Lang('cannot_be_blank'));
    }else{
	    $safeUsername = preg_replace('/[^a-zA-Z0-9\-_ ]/', '', $username);
    	if($safeUsername == '' || $safeUsername != $username){
            $error = true;
	        Antz::addFormError('username', $this->Lang('invalid_chars'));
    	}else{
        	$lowerUsername = strtolower($safeUsername);
            if($DB->countRows(cms_db_prefix().'iusers', "LOWER(username) = '{$safeUsername}'")>0){
	            $error = true;
    	        Antz::addFormError('username', $this->Lang('already_registered'));
        	};
            if(in_array(strtolower($username), $DISALLOWED_USERNAMES)){
	            $error = true;
    	        Antz::addFormError('username', $this->Lang('disallowed_username'));
        	};
    	};
	};

    // password
    if(strlen($password) < 6 || strlen($password) > 20){
        $error = true;
        Antz::addFormError('password', $this->Lang('6-20_chars'));
    }else if($password != $confirmPassword){
    	$error = true;
    	Antz::addFormError('confirm_password');
    }
    // email
    if(trim($email)==''){
        $error = true;
        Antz::addFormError('email', $this->Lang('cannot_be_blank'));
    }else{
        if(!Antz_Filter::checkEmail($email)){
            $error = true;
            Antz::addFormError('email', $this->Lang('invalid_chars'));
        }else{
            if($DB->countRows(cms_db_prefix().'iusers', "email_md5 = '{$emailMD5}'")>0){
                $error = true;
                Antz::addFormError('email', $this->Lang('already_registered'));
            };
        };
    };
    if(trim($email) != '' && $DB->countRows(cms_db_prefix().'iusers', "new_email = '{$email}'")>0){
    	$error = true;
        Antz::addFormError('email', $this->Lang('already_registered'));
    };

    // Name
    $fName = substr($fName, 0, 24);
    $lName = substr($lName, 0, 24);
    if(in_array('first_name', $showFields)){
	    if($insistFirstName && $fName == ''){
    	    $error = true;
        	Antz::addFormError('fName');
	    }else{
    	    if(strlen($fName)>12){
        	    $error = true;
            	Antz::addFormError('fName', $this->Lang('max_12_chars'));
        	};
	    };
    };

    if(in_array('last_name', $showFields)){
	    if($insistLastName && $lName == ''){
	        $error = true;
	        Antz::addFormError('lName');
	    }else{
	        if(strlen($lName)>12){
	            $error = true;
	            Antz::addFormError('lastName', $this->Lang('max_12_chars'));
	        };
	    };
    };

    // country and city
    if(in_array('country', $showFields)){
	    if($this->GetConfig('fe_country_required') == 1 && ($country == '' || $DB->countRows(cms_db_prefix().'iusers_countries', "id = '{$country}'")==0)){
	        $error = true;
	        Antz::addFormError('country');
	    };
    };
	if(in_array('city', $showFields)){
	    if($this->GetConfig('fe_city_required') == 1 && ($city == 0 || $DB->countRows(cms_db_prefix().'iusers_cities', "id = '{$city}'")==0)){
	        $error = true;
	        Antz::addFormError('city');
	    };
	};
	if(in_array('tnc', $showFields)){
	    // terms and coditions
	    if($tnc != 1){
	        $error = true;
	        Antz::addFormError('tnc', $this->Lang('must_agree_tnc'));
	    }
	};
	if(in_array('sex', $showFields)){
	    // terms and coditions
	    if($sex != 'm' && $sex != 'f' && $sex != '0'){
	        $error = true;
	        Antz::addFormError('sex');
	    }
	};

	// hookup to other modules
	$hookParams = array(
		'error' => false,
		'errors' => array()
	);
	$newParams = Antz::Hookup('IUsers_RegisterCheck', $hookParams);
	$hookParams = $newParams['params'];
	unset($newParams);
	if($hookParams['error']){
		$error = true;
		if(count($hookParams['errors'])>0){
			foreach($hookParams['errors'] as $errorMsg){
				Antz::addError($errorMsg);
			};
		};
	};

    if(!$error){
        // safe to process

        if(!in_array('subscribe', $showFields)){
        	$subscribe = $this->GetConfig('auto_subscribe_new_users');
        };

        $dbParams = array(
            'username' => $username,
            'email_crypt' => $CRYPT->crypt($email),
            'email_md5' => $emailMD5,
            'pass' => $CRYPT->crypt($password),
            'business_name' => $busname,
            'first_name' => $fName,
            'last_name' => $lName,
            'register_tstamp' => time(),
            'email_subscriber' => $subscribe,
            'dob' => $dob,
            'sex' => $sex
        );

        if($this->GetConfig('email_verification')==1){
            // email verification is required
            $dbParams['new_email'] = strtolower($email);
            $hashOrig = rand();
            $hash = md5($hashOrig);
            $dbParams['new_email_hash'] = $hash;
            $dbParams['status'] = 2;
            $emailVerification = true;
        }else{
            // user is fully registered and ready to go
            $dbParams['status'] = 1;
            $emailVerification = false;
            $hash = '';
        };

        // insert the user into the database
        $userid = $DB->insert(cms_db_prefix().'iusers', $dbParams);

		// used later for hookup
        $uData = $dbParams;

        // register their belonging to the groups
        foreach($groups as $k=>$v){
            $v = preg_replace('/[^a-zA-Z0-9_\- ]/', '', $v);
            if($DB->countRows(cms_db_prefix().'iusers_groups', "keyname = '{$v}'")==0) continue;
            $DB->insert(cms_db_prefix().'iusers_to_groups', array('group_key'=>$v, 'user_id'=>$userid));
        };

        // send the welcome message
        $loginId = $this->GetConfig('login_id');

        if($this->GetConfig('secure_login')==1){
            $loginUrl = str_replace('http://', 'https://', $Antz->getUrlById($loginId));
        }else{
            $loginUrl = $Antz->getUrlById($loginId);
        };

        $sitename = $DB->oneValue(cms_db_prefix().'siteprefs', 'sitepref_value', "sitepref_name = 'sitename'");
        $subject = $this->Lang('welcome_to', $sitename);
        if($emailVerification) $emailTemplate = 'admin.register.verify.php';
        else $emailTemplate = 'admin.register.noverify.php';

        $emailParams = array(
            'login_url' => $loginUrl,
            'name' => $fName.' '.$lName,
            'email' => $email,
            'username' => $username,
            'password' => $password,
            'sitename' => $sitename,
            'email_verification_url' => $Antz->addParamsToUrl($Antz->getUrlById($this->GetConfig('email_verification_id')), array('email'=>$email, 'hash'=>$hash)),
            'email_verification_url_htmlentities' => $Antz->addParamsToUrl($Antz->getUrlById($this->GetConfig('email_verification_id')), array('email'=>$email, 'hash'=>$hash), true),
        );
        $msg = $this->ProcessEmailTemplate($emailTemplate, $emailParams);

        $toFrom = array(
            'toName' => $fName.' '.$lName,
            'toEmail' => $email
        );
        Antz_Email::sendRaw($subject, $msg, $toFrom, true);

        // report success to the user
        if($this->GetConfig('email_verification')!='0'){
            $successMsg = $this->Lang('success_check_email');
            $autoLogin = false;
        }else{
            $successMsg = $this->Lang('success_no_check_email');
            $uData = $DB->fetchRow("SELECT * FROM {$this->config['db_prefix']}iusers WHERE id = '{$userid}'");
			$autoLogin = true;
        };

        Antz::addSuccess($successMsg);

        // hookup to other modules
        $uData['password'] = $password;
        $uData['email'] = $email;
        $uData['id'] = $userid;
		$hookParams = array('user_data' => $uData);
		$newParams = Antz::Hookup('IUsers_RegisterProcess', $hookParams);
		$hookParams = $newParams['params'];
		unset($newParams);

		if($autoLogin){
			$USER->login($uData);

            // hookup to other modules
			$hookParams = array('user_data' => $uData);
			$newParams = Antz::Hookup('IUsers_LoginProcess', $hookParams);
			unset($newParams);

            // SMF integration
            if(is_object($this->IUsers2SMF) && $this->IUsers2SMF instanceof IUsers2SMF){
            	$smfParams = array(
                    'username' => $uData['username'],
                    'password' => $uData['password']
                );
                $this->IUsers2SMF->login($smfParams, Antz::getLastPage());
            };
            // end SMF integration

		}



        Antz::goLastPage();

    }else{
        // there was a form error
        Antz::addError($this->Lang('fields_are_empty'));

    };// end if error

};// end if submitted

$countries = $DB->fetchAll("SELECT * FROM ".cms_db_prefix().'iusers_countries ORDER BY title ASC');
if(post('country')=='') $country = $this->GetConfig('default_country');
else $country = post('country');
$country = strtolower($country);
$minPopulation = (int) $this->GetConfig('cities_min_population');
$cities = $DB->fetchAll("SELECT * FROM {$this->config['db_prefix']}iusers_cities WHERE LOWER(country_id) = '{$country}' AND population >= {$minPopulation} ORDER BY title ASC");

$countryOptions = array();
foreach($countries as $k=>$v){
	$countryOptions[$v['id']] = $v['title'];
}
$cityOptions = array();
foreach($cities as $k=>$v){
	$cityOptions[$v['id']] = $v['title'];
}


// gonna define the form fields as an array because other modules can add their fields to it (See Antz::Hookup())
$formFields = array(
	array(
		'name' => 'username',
		'value' => post('username'),
		'type' => 'text',
		'label' => $this->Lang('username'),
		'required' => true
	),
	array(
		'name' => 'email',
		'value' => post('email'),
		'type' => 'text',
		'label' => $this->Lang('email'),
		'required' => true
	),
	array(
		'name' => 'confirm_email',
		'value' => post('confirm_email'),
		'type' => 'text',
		'label' => $this->Lang('confirm_email'),
		'extra' => array(
					array(
						'command' => 'addAttribute',
						'params' => array(
							"'autocomplete'",
							"'off'"
						)

					)
				),
		'required' => true
	),
	array(
		'name' => 'password',
		'value' => post('password'),
		'type' => 'password',
		'label' => $this->Lang('password'),
		'required' => true
	),
	array(
		'name' => 'confirm_password',
		'value' => post('confirm_password'),
		'type' => 'password',
		'label' => $this->Lang('confirm_password'),
		'required' => true
	)
);

if(in_array('business_name', $showFields)){
	$formFields[] =
	array(
		'name' => 'business_name',
		'value' => post('business_name'),
		'type' => 'text',
		'label' => $this->Lang('business_name')
	);
};
if(in_array('first_name', $showFields)){
	$formFields[] =
	array(
		'name' => 'first_name',
		'value' => post('first_name'),
		'type' => 'text',
		'label' => $this->Lang('first_name'),
		'required' => (bool) $this->GetConfig('fe_insist_fname')
	);
};
if(in_array('last_name', $showFields)){
	$formFields[] =
	array(
		'name' => 'last_name',
		'value' => post('last_name'),
		'type' => 'text',
		'label' => $this->Lang('last_name'),
		'required' => (bool) $this->GetConfig('fe_insist_lname')
	);
};
if(in_array('address', $showFields)){
	$formFields[] =
	array(
		'name' => 'address',
		'value' => post('address', $uData['address']),
		'type' => 'textarea',
		'label' => $this->Lang('address')
	);
};
if(in_array('country', $showFields)){
	$formFields[] =
	array(
		'name' => 'country',
		'value' => post('country', $this->GetConfig('default_country')),
		'type' => 'select',
		'label' => $this->Lang('country'),
		'options' => $countryOptions,
		'id' => 'countrySel',
		'extra' => array(
				array(
				'command' => 'addJsEvent',
				'params' => array(
					"'onchange'",
					"'IUsers_Places.getCitiesForCountry(\'{$this->config['root_url']}\', this, \'citySel\')'"
				)
			)
		),
	  'required' => (bool) $this->GetConfig('fe_country_required')
	);
};
if(in_array('city', $showFields)){
	$formFields[] =
	array(
		'name' => 'city',
		'value' => post('city', $uData['city']),
		'type' => 'select',
		'label' => $this->Lang('city'),
		'options' => $cityOptions,
		'id' => 'citySel',
	 'required' => (bool) $this->GetConfig('fe_city_required')
  );
};
if(in_array('dob', $showFields)){
	$formFields[] =
	array(
		'name' => 'dob',
		'value' => post('dob', $uData['dob']),
		'type' => 'select',
		'label' => $this->Lang('dob')
	);
};
if(in_array('sex', $showFields)){
	$formFields[] =
	array(
		'name' => 'sex',
		'value' => post('sex'),
		'type' => 'text',
		'label' => $this->Lang('sex')
	);
};
if(in_array('subscribe', $showFields)){
	$formFields[] =
	array(
		'name' => 'subscribe',
		'value' => '1',
		'type' => 'checkbox',
		'label' => $this->Lang('subscribe'),
		'checked' => post('subscribe', $this->GetConfig('auto_subscribe_new_users'))
	);
};
if(in_array('tnc', $showFields)){
	$formFields[] =
	array(
		'name' => 'tnc',
		'value' => '1',
		'type' => 'checkbox',
		'label' => $this->Lang('tnc_understood', $Antz->getUrlById($this->GetConfig('tnc_id'))),
		'checked' => post('checked', '0')
	);
};


// implement the hook to get extra form fields from other modules
$hookParams = array('form_fields' => $formFields);
$newParams = $Antz->Hookup('IUsers_RegisterForm', $hookParams);
$formFields = $newParams['params']['form_fields'];
unset($newParams);


// ready to create our form

if($this->GetConfig('auto_forms')){

	// prepare the structure for auto form generation

	$form = Antz::makeRapidForm($formFields, $this->Lang('register_legend'), 'IUsers_Register');

	$form->addSubmit($this->Lang('submit'));

	echo $form->render();

}else{
	// assigning form components to smarty variables and processing template
	if($this->GetConfig('wrap_form_components')) $wrap = true;
	else $wrap = false;
	if($this->GetConfig('show_labels')) $labels = true;
	else $labels = false;

	foreach($formFields as $field){
		$component = Antz::makeFormComponent($field, $wrap, $labels);
		$this->smarty->assign('fc_'.$field['name'], $component->render());
	};

	$this->smarty->assign('register_intelliform_seed', Antz_IntelliForm::seed('IUsers_Register'));

	echo $this->ProcessTemplate('register.tpl');

}


/* old way before Antz::Hookup implementation
$Antz = Antz::registry('Antz');
$form = Antz::newObject('Antz_Form', __FILE__);
$block = $form->add('full');
$fs = $block->add($this->Lang('registration_details'));
$accessGroups = $DB->fetchAll('SELECT * FROM '.cms_db_prefix().'iusers_groups');
$countries = $DB->fetchAll("SELECT * FROM ".cms_db_prefix().'iusers_countries ORDER BY title ASC');
$country = post('country', $defaultCountry);
$cities = $DB->fetchAll("SELECT * FROM {$this->config['db_prefix']}iusers_cities WHERE country_id = '{$country}' ORDER BY title ASC");

// create the form for making a new user
$form = Antz::newObject('Antz_Form', __FILE__);
$block = $form->add('full');
$fs = $block->add($this->Lang('new_details'));
$fs->addInput('hidden', 'action', '', 'new');
$fs->addInput('text', 'username', $this->Lang('username'), post('username'));
$fs->addInput('text', 'email', $this->Lang('email'), post('email'));
$fs->addInput('password', 'password', $this->Lang('password'), post('password'));
$fs->addInput('text', 'fName', $this->Lang('first_name'), post('fName'));
$fs->addInput('text', 'lName', $this->Lang('last_name'), post('lName'));
$ctrySel = $fs->addSelect('country', $this->Lang('country'), post('country', $defaultCountry));
//var_dump($countries);exit;
foreach($countries as $k=>$v){
    $ctrySel->add($v['title'], $v['id']);
};
$citySel = $fs->addSelect('city', $this->Lang('city'));
foreach($cities as $k=>$v){
    $citySel->add($v['title'], $v['id']);
};

$ctrySel->addJsEvent('onchange', 'IUsers_Places.getCitiesForCountry(\''.$this->config['root_url'].'\', this, \''.$citySel->getId().'\')');
$grp = $fs->addCheckboxGroup('tnc');

$tncUrl = $Antz->getUrlByAlias($this->GetConfig('tnc_url'));

$chk = $grp->add('tnc', $this->lang('tnc_understood', $tncUrl), '1', post('tnc'));
$fs->addInput('submit', 'submitBtn', '&nbsp;', $this->Lang('submit'));

echo $form->render();

*/